package com.ruoyi.framework.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.dyun.tool.mybatis.util.MPContextHolder;
import com.ruoyi.framework.config.AliossConfig;
import net.dreamlu.mica.core.spring.SpringContextUtil;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.utils.FileUtil;
import net.dreamlu.mica.props.MicaUploadProperties;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author dyun
 */
public class FileDyUtils {

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    public static String getResourcePath() {
        return FileDyUtils.class.getResource("/").getPath();
    }

    public static String getUploadPath() {
        String tenantId = MPContextHolder.getTenantId();
        if ($.isBlank(tenantId)) {
            tenantId = "none";
        }
        // 示例: /tenant-none/2020-01-01/

        // alioss规则不同，不能以“/”或者“\”开头。
        String url = "tenant-" + tenantId + "/" + DateUtil.today() + "/";
        if (AliossConfig.ossClient != null) {
            return url;
        }
        return "/" + url;
    }

    /**
     * 重命名文件，避免文件覆盖
     */
    public static String renameFile(String originalFilename) {
        return IdUtil.fastUUID()
                + "."
                + $.toStr(FileUtil.getFileExtension(originalFilename), "png");
    }

    /**
     * 重命名文件，避免文件覆盖
     */
    public static String renameFile(String originalFilename, boolean keepOriginalFilename) {
        return IdUtil.fastUUID()
                + "_"
                + FileUtil.getPathWithoutExtension(originalFilename)
                + "."
                + $.toStr(FileUtil.getFileExtension(originalFilename), "png");
    }

    /**
     * 获取真实文件名称
     */
    public static String getRealDownloadFileName(String fileName) {
        return fileName.substring(fileName.indexOf("_") + 1);
    }

    /**
     * 文件名称验证
     *
     * @param fileName 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String fileName) {
        return fileName.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    public static String getFileDownloadPath(String fileName) {
        String downloadPath = SpringContextUtil.getBean(MicaUploadProperties.class).getSavePath() + "/download/" + fileName;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
